var createError = require('http-errors');
let express = require('express');
let path = require('path');
let session = require('express-session');//引入session
let { SECRECT } = require('./utils/CONSTANT');
let app = express();

// let cookieParser = require('cookie-parser');//引入cookie

//引入自定义中间件
let indexRouter = require('./routes/index');
let categoryRouter = require('./routes/category');
let goodsRouter = require('./routes/goods');
let shopcarRouter = require('./routes/shopcar');
let userRouter = require('./routes/user');
// let demoRouter = require('./routes/demo');
let intercept=require('./utils/intercept');

//允许跨域
app.use((req, res, next) => {
    // res.set('Access-Control-Allow-Origin','*');//允许跨域的请求源
    res.set('Access-Control-Allow-Origin', req.headers.origin);//允许跨域的请求源
    res.set('Access-Control-Allow-Credentials', true);//允许跨域后session的存取
    res.set('Access-Control-Allow-Headers', 'token');//跨域时，允许前端携带的请求头字段，若设置为*,则允许所有
    res.set("Access-Control-Allow-Methods", "GET, PUT, DELETE, POST, OPTIONS");
    next();
});


// 静态中间件
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));//静态资源

//使用cookie
// app.use(cookieParser());
//使用session
app.use(session({
    secret: SECRECT,      //加密秘钥(签名) 必填，否则会报错
    resave: true,       //是否强制刷新session存储器  true 刷新          可选
    saveUninitialized: false,           //是否保存未初始化的session   可选
    cookie: {
        maxAge: 1000 * 60 * 10        //过期时间   10分钟     可选的
    }
}));

//路由中间件
app.use('/', indexRouter);//首页
app.use('/category', categoryRouter);//分类
app.use('/goods', goodsRouter);//商品
app.use('/user', userRouter);//用户
// app.use('/demo', demoRouter);

//登录拦截  未登录用户不可以访问购物车
app.use(intercept());

app.use('/shopcar', shopcarRouter);//购物车


// //自定义中间件
// app.use('/favicon.ico', (req, res, next) => {    //谷歌浏览器的图标请求
//   return;
// });

// //错误处理中间件
// // catch 404 and forward to error handler
// app.use(function (req, res, next) {
//   next(createError(404));
// });

// // error handler
// app.use(function (err, req, res, next) {
//   res.send({
//     code: err.status || 500,
//     msg: err.message,
//     tip: "接口地址不存在",
//     data: null
//   });
// });

module.exports = app;
